package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.BottomViewModel
import kotlinx.coroutines.launch

@Composable
fun Pages(navController: NavController) {
    val viewModel: BottomViewModel = viewModel()

    val pagerState = rememberPagerState(initialPage = 0, pageCount = { 4 })
    val scope = rememberCoroutineScope()

    HorizontalPager(state = pagerState) { page ->
        when (page) {
            0 -> Page1(navController = navController)
            1 -> Page2()
            2 -> Page3()
            3 -> Page4(navController = navController)
        }
    }

    LaunchedEffect(viewModel.selectedTab) {
        scope.launch {
            pagerState.animateScrollToPage(viewModel.selectedTab)
        }
    }

    LaunchedEffect(pagerState.currentPage) {
        if (viewModel.selectedTab != pagerState.currentPage) {
            viewModel.selectedTab = pagerState.currentPage
        }
    }
}